import store from './platform/StorageUtil';
import Constants from "./platform/Constants";

let rootUrl = '';

const request = (url, method, body, cache = false,callback) => {
    //rootUrl
    url = getUrl(url);

    //cache
    let cacheUrl = getCacheUrl(url,body);
    if (cache) {
        store.get(cacheUrl,(cache) => {
            if (cache && cache.createTime) {
                if (timeInterval(cache.createTime) > cache.expireTime) {
                    console.log('http url cache expire ' + cache.expireTime);
                    requestExecute(url, method, body, cache,callback);
                } else {
                    console.log('http url get from cache: ' + url + "\n request: " + JSON.stringify(body) + '\n response: ' + cache.data);
                    let data = JSON.parse(cache.data);
                    if(callback){callback(data)}
                }
            } else {
                //console.log('http url cache is null, refresh request data');
                requestExecute(url, method, body, cache,callback);
            }
        });
    } else {
        requestExecute(url, method, body, cache,callback);
    }
};

const requestExecute = (url, method, body, cache = false,callback) => {
    let timeout = Constants.HTTP_TIMEOUT;
    let isOk = false;
    const fetchRequest = new Promise((resolve, reject) => {
        fetch(url, {
            method: method,
            headers: {
                // 'Content-Type': 'application/json;charset=utf-8',
                // "uid": Constants.uid | '',
                // "token": Constants.token,
                // "version": Constants.version,
                // "os": Constants.os,
                // "osVersion": Constants.osVersion,
                // "model": Constants.model,
                // "deviceId": Constants.deviceId
            },
            body: JSON.stringify(body)
        }).then((response) => {
            isOk = !!response.ok;
            return response.json();
        }).then((responseData) => {
            //console.log('http url: ' + url + "\n request: " + JSON.stringify(body) + '\n response: ' + JSON.stringify(responseData));
            if (isOk) {
                if (cache) {
                    let cache = {
                        createTime: new Date().getTime(),
                        expireTime: Constants.HTTP_EXPIRE_TIME,
                        data: JSON.stringify(responseData)
                    };
                    let cacheUrl = getCacheUrl(url,body);
                    /*store.save(cacheUrl, cache).then(() => store.get(cacheUrl)).then((cache) => {
                        console.log('http save cache: ' + JSON.stringify(cache));
                    });*/
                    store.save(cacheUrl, cache,(cache) => {
                        //console.log('http save cache: ' + JSON.stringify(cache));
                    });
                }
                resolve(responseData);
            } else {
                reject(responseData);
            }
        }).catch((error) => {
            reject(error);
        });
    });

    //定义一个延时函数
    const timeoutRequest = new Promise((resolve, reject) => {
        setTimeout(reject, timeout, 'Request timed out');
    });

    //竞时函数，谁先完成调用谁
    return Promise.race([fetchRequest, timeoutRequest])
        .then(res => {
            //return res
            if(callback){callback(res)}
        }, m => {
            //throw new Error(m);
            // if(callback){callback('err:'+m)}
            if(callback){callback({code:501,msg:'timeout'})}
        });
};

const setRootUrl = (root) => {
    rootUrl = root;
};

const getUrl = (url) => {
    let rootUrl = url;
    if(rootUrl.indexOf('/') === 0){
        rootUrl = Constants.defaultrootaddr +url;
    }
    return rootUrl;
};

const timeInterval = (lastTime) => {
    let now = new Date();
    let curTime = now.getTime();
    let interval = Number(curTime) - Number(lastTime);
    let r = Math.round(interval / 1000);
    console.log('cache data timeInterval=' + r+'秒');
    return interval;
};

const checkForceCache = (url) => {
    let urls = [
        Constants.EOSURL + '/chain/get_account',
        Constants.EOSURL+'/history/get_key_accounts'
    ];
    return urls.contains(url);
};

const getCacheUrl = (url,req) => {
    return url + '/' + JSON.stringify(req);
};

const checkCacheValid = (cache) => {
    if (cache && cache.createTime) {
        if(timeInterval(cache.createTime) < cache.expireTime){
            //console.log('checkCacheValid true');
            return true;
        }
    }
    return false;
};

export default {
    request,
    requestExecute
};